<template>
  <div>
    <header class="header">
      <div class="header-left">
        <img src="@/assets/svgs/left.svg" @click="router.push('/teacher/dashboard')" alt="Logo" class="back-icon" />
      </div>
      <div class="header-center">
        <span class="title">课堂质量实时反馈</span>
      </div>
      <div class="header-right">
        <el-button @click="confirmAddFeedback" type="text" class="feedback-button">发问卷</el-button>
      </div>
    </header>
    <div class="feedback-card-list">
      <div v-for="feedback in feedbacks" :key="feedback.surveyId" class="feedback-card">
        <div style="display: none;">{{ console.log('当前反馈数据:', feedback) }}</div>
        <div class="feedback-title">{{ feedback.surveyName }}</div>
        <div class="feedback-dates" style="margin-top: 10px;">开始时间：{{ formatDate(feedback.createTime) }}</div>
        <div class="feedback-submission" style="margin-top: 10px;">
          <div class="submission-label" style="font-size: 14px; color: gray; display: inline;">提交人数：</div>
          <div class="submission-number" style="display: inline;">{{ feedback.submit_count }}/{{ feedback.sum }}</div>
        </div>
        <el-button @click="viewResults(feedback.surveyId)" class="result-button"
          @mouseenter="() => console.log('即将点击的surveyId:', feedback.surveyId)">
          统计结果
        </el-button>
      </div>
    </div>

    <!-- 修改问卷名称输入对话框样式 -->
    <el-dialog v-model="showNameDialog" title="输入问卷名称" width="400px" :close-on-click-modal="false"
      :close-on-press-escape="false" custom-class="custom-message-box">
      <div class="dialog-content">
        <el-input v-model="surveyName" placeholder="请输入问卷名称" @keyup.enter="handleNameConfirm" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showNameDialog = false" class="dialog-button">
            取消
          </el-button>
          <el-button type="primary" @click="handleNameConfirm" class="dialog-button custom-confirm-button"
            style="background-color: #13227a; border-color: #13227a;">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { surveyListService, addSurveyService } from "@/api/feedback";
import { useCounterStore } from "@/stores/counter";

const store = useCounterStore();
const router = useRouter();
const route = useRoute();
const feedbacks = ref([]);
const surveyName = ref(''); // 添加问卷名称的响应式变量
const showNameDialog = ref(false); // 控制问卷名称输入框的显示
const loading = ref(false);

// 获取反馈列表
const fetchFeedbacks = async () => {
  loading.value = true;
  try {
    const courseManageId = store.courseManageId; // 从状态管理中获取课程ID
    console.log('课程ID:', courseManageId); // 调试信息

    const response = await surveyListService(courseManageId);
    if (response.code === 0 && response.data) {
      feedbacks.value = response.data.map(feedback => ({
        surveyId: feedback.surveyId,
        surveyName: feedback.surveyName,
        createTime: feedback.createTime,
        submit_count: Number(feedback.submit_count) || 0, // 已提交人数
        sum: Number(feedback.sum) || 0 // 总人数
      }));
    } else {
      throw new Error('获取反馈列表失败');
    }
  } catch (error) {
    console.error('获取反馈列表失败:', error);
    ElMessage.error('获取反馈列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 添加反馈
const addFeedback = async () => {
  try {
    if (!surveyName.value.trim()) {
      throw new Error('问卷名称不能为空');
    }

    const classId = store.courseManageId; // 获取课程ID

    const params = {
      surveyName: surveyName.value,
      courseManageId: Number(classId),
    };

    console.log('发送请求参数:', JSON.stringify(params));
    const result = await addSurveyService(params);
    if (result && result.code === 0) {
      ElMessage.success('问卷添加成功');
      showNameDialog.value = false;  // 关闭对话框
      surveyName.value = '';        // 清空输入
      await fetchFeedbacks();
    } else {
      throw new Error(result?.message || '创建失败');
    }
  } catch (error) {
    console.error('创建问卷错误:', error);
    ElMessage.error(error.message || '创建问卷失败');
  }
};

// 组件挂载时获取数据
onMounted(async () => {
  await fetchFeedbacks();
});

function formatDate(date) {
  const options = { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false };
  return new Intl.DateTimeFormat('zh-CN', options).format(new Date(date));
}

const confirmAddFeedback = () => {
  ElMessageBox.confirm('您确定要发问卷吗？', '提示', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'warning',
    customClass: 'message-confirm-box',
    distinguishCancelAndClose: true,
    confirmButtonClass: 'custom-confirm-button',
    cancelButtonClass: 'dialog-button',
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false,
    center: true,
    customStyle: {
      padding: '30px 40px 40px 40px',  // 增加左右内边距
      width: '400px',
      height: '200px'
    },
    buttonSize: 'large'
  }).then(() => {
    showNameDialog.value = true;
  }).catch(() => {
    // 取消操作
  });
};

const handleNameConfirm = () => {
  if (!surveyName.value.trim()) {
    ElMessage.warning('请输入问卷名称');
    return;
  }
  addFeedback();
  showNameDialog.value = false;
  surveyName.value = ''; // 清空输入
};

const viewResults = (surveyId) => {
  console.log('viewResults被调用，surveyId:', surveyId);
  router.push({
    path: `/teacher/feedback/result/${surveyId}`,
    replace: true
  });
};
</script>

<style>
.el-message-box {
  padding: 30px 40px 40px 40px !important;
  width: 400px !important;
  height: 200px !important;
  display: flex !important;
  flex-direction: column !important;
}

.el-message-box__content {
  flex: 1 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  padding: 30px 0 !important;
}

.el-message-box__btns {
  padding: 20px 20px 0 20px !important;
  margin: 0 !important;
  display: flex !important;
  justify-content: flex-end !important;
  gap: 10px !important;
}

.el-message-box .el-button--primary {
  background-color: #13227A !important;
  border-color: #13227A !important;
  color: white !important;
}
</style>

<style scoped>
.template {
  background-color: #F9FAFB;
}

.header {
  color: white;
  padding: 10px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #13227a;
}

.header-left {
  flex: 1;
}

.header-center {
  flex: 2;
  text-align: center;
}

.header-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
}

.back-icon {
  cursor: pointer;
}

.feedback-button {
  background-color: #13227a;
  border: 1px solid white;
  color: white;
  width: 120px;
  height: 40px;
}

.feedback-card-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-top: 20px;
  padding: 0 40px;
}

.feedback-card {
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.feedback-title {
  font-weight: bold;
  color: black;
  font-size: 20px;
}

.feedback-dates {
  color: gray;
  font-size: 14px;
}

.feedback-submission {
  color: darkgray;
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.result-button {
  background-color: #13227a;
  color: white;
  margin-top: auto;
  align-self: flex-end;
}

/* 输入框弹窗样式 */
:deep(.custom-message-box) {
  width: 400px !important;
  height: 200px !important;
  padding: 30px 20px !important;
}

/* 询问弹窗样式 */
:global(.el-message-box) {
  width: 400px !important;
  height: 200px !important;
  padding: 30px 20px 40px 20px !important;
  /* 增加底部内边距 */
  display: flex !important;
  flex-direction: column !important;
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
}

:global(.el-message-box .el-message-box__content) {
  flex: 1 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  padding: 30px 15px !important;
}

:global(.el-message-box .el-message-box__btns) {
  padding: 20px 20px 0 20px !important;
  /* 增加左右内边距 */
  margin: 0 !important;
  display: flex !important;
  justify-content: flex-end !important;
  gap: 10px !important;
}

/* 确认按钮样式 */
:global(.el-message-box .el-button--primary) {
  background-color: #13227A !important;
  border-color: #13227A !important;
  color: white !important;
}

:global(.el-message-box .el-button--primary:hover) {
  opacity: 0.9 !important;
}

/* 取消按钮样式 */
:global(.el-message-box .el-button) {
  padding: 12px 20px !important;
  min-width: 80px !important;
}

/* 遮罩层样式 */
:global(.v-modal) {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
}

.dialog-button {
  font-size: 14px !important;
  padding: 12px 20px !important;
  height: auto;
  min-width: 80px;
}

:deep(.el-dialog__headerbtn) {
  display: none;
}

:deep(.el-dialog__body) {
  padding: 0 !important;
}

:deep(.el-dialog) {
  position: absolute !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
}

:deep(.el-overlay) {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 统一两个弹窗的样式 */
:deep(.message-confirm-box),
:deep(.custom-message-box) {
  width: 400px !important;
  height: 200px !important;
  padding: 30px 20px !important;
}

/* 确认弹窗的特殊样式 */
:deep(.message-confirm-box) {
  display: flex !important;
  flex-direction: column !important;
}

:deep(.message-confirm-box .el-message-box__content) {
  flex: 1 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  padding: 30px 0 !important;
}

:deep(.message-confirm-box .el-message-box__btns) {
  padding: 20px 0 0 0 !important;
  margin: 0 !important;
}

/* 修改询问弹窗确认按钮颜色 */
:deep(.message-confirm-box .custom-confirm-button),
:deep(.el-message-box .custom-confirm-button) {
  background-color: #13227a !important;
  border-color: #13227a !important;
}

:deep(.message-confirm-box .custom-confirm-button:hover),
:deep(.el-message-box .custom-confirm-button:hover) {
  background-color: #13227a !important;
  border-color: #13227a !important;
  opacity: 0.9;
}

.dialog-button {
  font-size: 14px !important;
  padding: 12px 20px !important;
  height: auto;
  min-width: 80px;
}

/* 确保弹窗位置居中 */
:deep(.el-message-box),
:deep(.el-dialog) {
  position: absolute !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
}

/* 强制设置询问弹窗确认按钮颜色 */
:deep(.el-message-box .el-button--primary),
:deep(.el-message-box .custom-confirm-button) {
  background-color: #13227a !important;
  border-color: #13227a !important;
  color: white !important;
}

:deep(.el-message-box .el-button--primary:hover),
:deep(.el-message-box .custom-confirm-button:hover) {
  background-color: #13227a !important;
  border-color: #13227a !important;
  opacity: 0.9 !important;
}

/* 确保没有其他样式覆盖 */
:deep(.el-message-box .el-button--primary:focus),
:deep(.el-message-box .el-button--primary:active),
:deep(.el-message-box .custom-confirm-button:focus),
:deep(.el-message-box .custom-confirm-button:active) {
  background-color: #13227a !important;
  border-color: #13227a !important;
}
</style>
